package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: Zhou ShiYang
 * @Description:
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Integer id){
        // 查询是否存在
        User user = new User();
        user.setId(id);
        user = userMapper.selectOneUser(user);
        if (user == null){
            // 不存在，不能删除
            return 0;
        }else {
            return userMapper.deleteUserByPrimaryKey(id);
        }
    }

    /**
     * 修改
     * @param user
     */
    @Override
    public int update(User user){
        // 是否重复
        User user1 = new User();
        user1.setMobile(user.getMobile());
        user1 = userMapper.selectOneUser(user1);
        // 当前的用户名有用户设置了
        if (user1 != null) {
            // 用户名重复
            if (!user1.getId().equals(user.getId())) {
                return 0;
            }
        }
        return userMapper.updateUserByPrimaryKeySelective(user);
    }

    /**
     * 增加
     * @param user
     */
    @Override
    public int add(User user){
        // 验证用户名是否重复
        User user1 = new User();
        user1.setMobile(user.getMobile());
        user1 = userMapper.selectOneUser(user1);
        if (user1 != null){
            // 用户名重复
            return 0;
        }
        return userMapper.insertUserSelective(user);
    }

    /***
     * 查询条件Patient
     * @return
     */
    @Override
    public List<User> find(User user) {
        List<User> users = userMapper.selectUser(user);
        return users;
    }
}
